import axios from 'axios'
import { Message } from 'view-ui-plus'
import { useUserStore } from '@/stores/user'
import router from '@/router'

// 创建 axios 实例
const service = axios.create({
    baseURL: '',
    timeout: 15000,
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    }
})

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        const userStore = useUserStore()
        if (userStore.token) {
            config.headers['Authorization'] = userStore.token
        }
        return config
    },
    (error) => {
        console.log(error)
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        const res = response.data
        if (res.code !== 200) {
            Message.error(res.msg || '系统错误')

            // 401: Token失效
            if (res.code === 401) {
                const userStore = useUserStore()
                userStore.logout()
                router.push('/login')
            }
            return Promise.reject(new Error(res.msg || '系统错误'))
        }
        return res.data
    },
    (error) => {
        console.log('err' + error)
        Message.error(error.msg || '请求失败')
        return Promise.reject(error)
    }
)

export default service